package com.example.demo.controller;

import com.example.demo.response.ApiResponse;
import com.example.demo.service.NewTaskFlowService;
import com.example.demo.service.TaskRoutingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 任务分发与处理人分配一体化控制器
 * 将任务分发和设置处理人两个功能合并到一个接口中实现
 */
@RestController
@RequestMapping("/api/task-distribution")

public class TaskDistributionController {

    //private static final logger log = loggerFactory.getlogger(TaskDistributionController.class);

    @Autowired
    private NewTaskFlowService newTaskFlowService;

    @Autowired
    private TaskRoutingService taskRoutingService;


    @PostMapping("/batch-distribute-and-assign/datasource/{dataSourceId}")
    public ResponseEntity<ApiResponse<TaskDistributionResult>> batchDistributeAndAssignByDataSource(
             @PathVariable Long dataSourceId,
            HttpServletRequest request) {

        //log.infp("开始为数据源ID: {} 执行批量分发任务并分配处理人", dataSourceId);

        try {
            // 第一步：批量分发任务流程关系
            //log.infp("第一步：开始批量分发任务流程关系");
            int distributedCount = newTaskFlowService.batchDistributeTaskFlows(dataSourceId);
            //log.infp("第一步完成：成功分发 {} 条任务流程关系", distributedCount);

            // 第二步：批量分配审批人
            //log.infp("第二步：开始批量分配审批人");
            int assignedCount = taskRoutingService.batchAssignApproversByDataSource(dataSourceId);
            //log.infp("第二步完成：成功为 {} 个任务分配审批人", assignedCount);

            // 构建结果
            TaskDistributionResult result = new TaskDistributionResult();
            result.setDistributedCount(distributedCount);
            result.setAssignedCount(assignedCount);
            result.setDataSourceId(dataSourceId);
            result.setSuccess(true);
            result.setMessage(String.format("成功分发 %d 条任务流程关系，并为 %d 个任务分配了审批人", 
                                          distributedCount, assignedCount));

            //log.infp("任务分发与处理人分配完成：数据源ID={}, 分发数量={}, 分配数量={}", 
                    //dataSourceId, distributedCount, assignedCount);

            return ResponseEntity.ok(
                    ApiResponse.success(result, result.getMessage(), request.getRequestURI(), null));

        } catch (Exception e) {
            //log.error("为数据源ID: {} 执行批量分发任务并分配处理人失败: {}", dataSourceId, e.getMessage(), e);
            
            TaskDistributionResult result = new TaskDistributionResult();
            result.setDataSourceId(dataSourceId);
            result.setSuccess(false);
            result.setMessage("批量分发任务并分配处理人失败: " + e.getMessage());
            
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(result.getMessage(), request.getRequestURI()));
        }
    }


    @PostMapping("/batch-distribute-and-assign/flow/{flowId}")
    public ResponseEntity<ApiResponse<TaskDistributionResult>> batchDistributeAndAssignByFlow(
             @PathVariable Long flowId,
            HttpServletRequest request) {

        //log.infp("开始为流程ID: {} 执行批量分发任务并分配处理人", flowId);

        try {
            // 第一步：批量分发任务流程关系
            //log.infp("第一步：开始批量分发任务流程关系");
            int distributedCount = newTaskFlowService.batchDistributeTaskFlowsByFlowId(flowId);
            //log.infp("第一步完成：成功分发 {} 条任务流程关系", distributedCount);

            // 第二步：批量分配审批人（按流程）
            //log.infp("第二步：开始批量分配审批人");
            int assignedCount = taskRoutingService.batchAssignApprovers(flowId);
            //log.infp("第二步完成：成功为 {} 个任务分配审批人", assignedCount);

            // 构建结果
            TaskDistributionResult result = new TaskDistributionResult();
            result.setDistributedCount(distributedCount);
            result.setAssignedCount(assignedCount);
            result.setFlowId(flowId);
            result.setSuccess(true);
            result.setMessage(String.format("成功分发 %d 条任务流程关系，并为 %d 个任务分配了审批人", 
                                          distributedCount, assignedCount));

            //log.infp("任务分发与处理人分配完成：流程ID={}, 分发数量={}, 分配数量={}", 
                    //flowId, distributedCount, assignedCount);

            return ResponseEntity.ok(
                    ApiResponse.success(result, result.getMessage(), request.getRequestURI(), null));

        } catch (Exception e) {
            //log.error("为流程ID: {} 执行批量分发任务并分配处理人失败: {}", flowId, e.getMessage(), e);
            
            TaskDistributionResult result = new TaskDistributionResult();
            result.setFlowId(flowId);
            result.setSuccess(false);
            result.setMessage("批量分发任务并分配处理人失败: " + e.getMessage());
            
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(result.getMessage(), request.getRequestURI()));
        }
    }

    /**
     * 任务分发结果DTO
     */
    public static class TaskDistributionResult {
        private Long dataSourceId;
        private Long flowId;
        private int distributedCount;
        private int assignedCount;
        private boolean success;
        private String message;

        // Getters and Setters
        public Long getDataSourceId() {
            return dataSourceId;
        }

        public void setDataSourceId(Long dataSourceId) {
            this.dataSourceId = dataSourceId;
        }

        public Long getFlowId() {
            return flowId;
        }

        public void setFlowId(Long flowId) {
            this.flowId = flowId;
        }

        public int getDistributedCount() {
            return distributedCount;
        }

        public void setDistributedCount(int distributedCount) {
            this.distributedCount = distributedCount;
        }

        public int getAssignedCount() {
            return assignedCount;
        }

        public void setAssignedCount(int assignedCount) {
            this.assignedCount = assignedCount;
        }

        public boolean isSuccess() {
            return success;
        }

        public void setSuccess(boolean success) {
            this.success = success;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }
}